$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '1') {
        window.location.href = '../index.html';
        return;
    }

    // 加载商品列表
    loadCommodities();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        localStorage.clear();
        window.location.href = '../index.html';
    });
});

// 加载商品列表
function loadCommodities() {
    const sellerId = localStorage.getItem('userId');
    
    $.ajax({
        url: `/api/commodity/seller/${sellerId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const commodities = response.data;
                const container = $('#commodityList');
                container.empty();
                
                commodities.forEach(commodity => {
                    container.append(`
                        <div class="commodity-item">
                            <div class="commodity-info">
                                <h3>${commodity.commodityName}</h3>
                                <div class="price">¥${commodity.price.toFixed(2)}</div>
                                <div class="stock">库存: ${commodity.stock}</div>
                                <div class="status">状态: ${commodity.status === 1 ? '已上架' : '已下架'}</div>
                            </div>
                            <div class="commodity-actions">
                                <button onclick="editCommodity(${commodity.commodityId})" class="edit-btn">编辑</button>
                                ${commodity.status === 1 ? 
                                    `<button onclick="offlineCommodity(${commodity.commodityId})" class="offline-btn">下架</button>` :
                                    `<button onclick="onlineCommodity(${commodity.commodityId})" class="online-btn">上架</button>`
                                }
                                <button onclick="deleteCommodity(${commodity.commodityId})" class="delete-btn">删除</button>
                            </div>
                        </div>
                    `);
                });
            }
        }
    });
}

// 删除商品
function deleteCommodity(commodityId) {
    if (!confirm('确定要删除这个商品吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/commodity/${commodityId}`,
        type: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                alert('删除成功');
                loadCommodities();
            } else {
                alert(response.message || '删除失败');
            }
        },
        error: function(xhr) {
            console.error('删除失败:', xhr);
            alert('删除失败，请重试');
        }
    });
}

// 下架商品
function offlineCommodity(commodityId) {
    if (!confirm('确定要下架这个商品吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/commodity/update/status`,
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            commodityId: commodityId,
            status: 0
        }),
        success: function(response) {
            if (response.code === 200) {
                alert('下架成功');
                loadCommodities();
            } else {
                alert(response.message || '下架失败');
            }
        },
        error: function() {
            alert('下架失败，请重试');
        }
    });
}

// 上架商品
function onlineCommodity(commodityId) {
    if (!confirm('确定��上架这个商品吗？')) {
        return;
    }
    
    $.ajax({
        url: `/api/commodity/update/status`,
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            commodityId: commodityId,
            status: 1
        }),
        success: function(response) {
            if (response.code === 200) {
                alert('上架成功');
                loadCommodities();
            } else {
                alert(response.message || '上架失败');
            }
        },
        error: function() {
            alert('上架失败，请重试');
        }
    });
}

// 编辑商品
function editCommodity(commodityId) {
    // 获取商品详情
    $.ajax({
        url: `/api/commodity/${commodityId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const commodity = response.data;
                // 填充表单
                $('#commodityId').val(commodity.commodityId);
                $('#commodityName').val(commodity.commodityName);
                $('#price').val(commodity.price);
                $('#stock').val(commodity.stock);
                // 显示编辑模态框
                $('#editModal').show();
            } else {
                alert(response.message || '获取���品信息失败');
            }
        },
        error: function() {
            alert('获取商品信息失败，请重试');
        }
    });
}

// 保存编辑
function saveEdit() {
    const commodityData = {
        commodityId: $('#commodityId').val(),
        commodityName: $('#commodityName').val(),
        price: parseFloat($('#price').val()),
        stock: parseInt($('#stock').val()),
        sellerId: localStorage.getItem('userId')
    };

    $.ajax({
        url: '/api/commodity/update',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify(commodityData),
        success: function(response) {
            if (response.code === 200) {
                alert('更新成功');
                $('#editModal').hide();
                loadCommodities();
            } else {
                alert(response.message || '更新失败');
            }
        },
        error: function() {
            alert('更新失败，请重试');
        }
    });
} 